package com.kt.dao.imp;

import com.kt.dao.CategoryDAO;
import com.kt.domain.Category;
import com.kt.utils.UtilDB;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class CategoryDAOImp implements CategoryDAO {
    public Category findByName(String name) {
        Category category = null;
        Connection connection = UtilDB.getConnection();
        ResultSet resultSet = null;
        String sql = "select * from category where cname = ?";
        PreparedStatement preparedStatement = null;
        try {
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, name);
            resultSet = preparedStatement.executeQuery();
            if (resultSet.next()) {
                category = new Category();
                category.setCid(resultSet.getInt("cid"));
                category.setCname(resultSet.getString("cname"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return category;
    }

    public int addCategory(Category category) {
        int result = 0;
        Connection connection = UtilDB.getConnection();
        PreparedStatement preparedStatement = null;
        String sql = "insert into category values(null, ?)";
        try {
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, category.getCname());
            result = preparedStatement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            UtilDB.close(connection);
        }

        return result;
    }
}
